﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using WorkFlowSystem.Common;
using WorkFlowSystem.DataBase;

namespace WorkFlowSystem
{
    public partial class PositionInfoEdit : Form
    {
        public PositionInfoEdit()
        {
            InitializeComponent();
            m_modify_mode = false;
        }

        #region 辅助方法
        public void SetMode(bool modify_mode, string pid)
        {
            m_modify_mode = modify_mode;
            if (m_position_info == null)
            {
                m_position_info = new PositionInfo();
                m_position_info.pid = pid;
            }
        }

        private void PositionInfoEdit_Load(object sender, EventArgs e)
        {
            comboBoxEx1.Items.Add("-");
            comboBoxEx1.SelectedIndex = 0;
            if (m_modify_mode)
            {
                if (init_modify_position() < 0)
                    this.Close();
            }
            else
            {
                if (init_add_position() < 0)
                    this.Close();
            }
        }

        private int load_position()
        {
            Logger.WriteLog("enter load_position");
            DBOperator db_op = new DBOperator();
            if (db_op.ConnectDB() < 0)
            {
                MessageBox.Show("无法连接服务器，请检查网络连接");
                return -1;
            }

            //获取pid的职位信息
            string sql = "select * from position_info where pid=@pid";
            DataTable dt = new DataTable();
            List<SqlParameter> para_list = new List<SqlParameter>();
            para_list.Add(new SqlParameter("@pid", m_position_info.pid));
            if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) < 0)
            {
                Logger.WriteLogError("get position info of [" + m_position_info.pid + "] fail");
                db_op.CloseDB();
                return -1;
            }
            m_position_info.p_name = dt.Rows[0]["p_name"].ToString();
            m_position_info.p_info = dt.Rows[0]["p_info"].ToString();
            m_position_info.p_did = dt.Rows[0]["p_did"].ToString();
            //get d_name by did
            sql = "select d_name from department where did=@did";
            para_list.Clear();
            para_list.Add(new SqlParameter("@did", m_position_info.p_did));
            dt.Clear();
            if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) < 0)
            {
                Logger.WriteLogError("cannot find dpt_name with did[" + m_position_info.p_did + "]");
                db_op.CloseDB();
                return -1;
            }
            if (dt.Rows.Count <= 0)
            {
                Logger.WriteLogError("cannot find dpt_name with did[" + m_position_info.p_did + "]");
                db_op.CloseDB();
                return -1;
            }
            m_position_info.d_name = dt.Rows[0]["d_name"].ToString();
            db_op.CloseDB();
            return 0;
        }

        private int init_add_position()
        {
            if (get_d_name() < 0)
            {
                MessageBox.Show("获取部门名称失败");
                return -1;
            }
            return 0;
        }

        private int init_modify_position()
        {
            if (get_d_name() < 0)
            {
                MessageBox.Show("获取部门名称失败");
                return -1;
            }

            //load data from database to memory
            if (load_position() < 0)
            {
                MessageBox.Show("加载部门信息失败");
                return -1;
            }
            //init控件
            textBoxX1.Text = m_position_info.p_name;
            comboBoxEx1.SelectedIndex = (comboBoxEx1.Items.IndexOf(m_position_info.d_name) < 0) ? 0 : comboBoxEx1.Items.IndexOf(m_position_info.d_name);
            richTextBoxEx1.Text = m_position_info.p_info;
            return 0;
        }

        private int get_d_name()
        {
            Logger.WriteLog("enter get_d_name");
            DBOperator db_op = new DBOperator();
            if (db_op.ConnectDB() < 0)
            {
                MessageBox.Show("无法连接服务器，请检查网络连接");
                return -1;
            }
            string sql = "select d_name from department";
            DataTable dt = new DataTable();
            if (db_op.ExecuteDataTable(sql, null, false, ref dt) < 0)
            {
                Logger.WriteLogError("get department info fail");
                MessageBox.Show("获取部门信息失败");
                db_op.CloseDB();
                return -1;
            }
            db_op.CloseDB();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                comboBoxEx1.Items.Add(dt.Rows[i]["d_name"].ToString());
            }
            return 0;
        }
        #endregion

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX1_Click(object sender, EventArgs e)
        {
            m_position_info.p_name = textBoxX1.Text;
            m_position_info.d_name = comboBoxEx1.SelectedItem.ToString();
            m_position_info.p_info = richTextBoxEx1.Text;

            DBOperator db_op = new DBOperator();
            if (db_op.ConnectDB() < 0)
            {
                MessageBox.Show("无法连接服务器，请检查网络连接");
                return;
            }

            string sql = "";
            DataTable dt = new DataTable();
            List<SqlParameter> para_list = new List<SqlParameter>();

            //获取部门id
            sql = "select did from department where d_name=@dpt_name";
            para_list.Add(new SqlParameter("@dpt_name", m_position_info.d_name));
            if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) < 0)
            {
                Logger.WriteLogError("cannot find did with this dpt_name[" + m_position_info.d_name + "]");
                MessageBox.Show("无此部门的ID");
                db_op.CloseDB();
                return;
            }
            if (dt.Rows.Count <= 0)
            {
                Logger.WriteLogError("cannot find did with this dpt_name[" + m_position_info.d_name + "]");
                MessageBox.Show("无此部门的ID");
                db_op.CloseDB();
                return;
            }
            m_position_info.p_did = dt.Rows[0]["did"].ToString();

            if (m_modify_mode)
            {
                sql = "update position_info set p_did=@p_did, p_name=@p_name, p_info=@p_info, p_update_uid=@update_uid, p_update_date=@update_date " +
                    "where pid=@pid";
            }
            else {
                sql = "insert into position_info(p_did, p_name, p_info, p_insert_uid, p_insert_date, p_update_uid, p_update_date) " +
                    "values(@p_did, @p_name, @p_info, @insert_uid, @insert_date, @update_uid, @update_date)";
            }
            para_list.Clear();
            para_list.Add(new SqlParameter("@pid", m_position_info.pid));
            para_list.Add(new SqlParameter("@p_did", m_position_info.p_did));
            para_list.Add(new SqlParameter("@p_name", m_position_info.p_name));
            para_list.Add(new SqlParameter("@p_info", m_position_info.p_info));
            para_list.Add(new SqlParameter("@insert_uid", CurrentUser.user_id));
            para_list.Add(new SqlParameter("@insert_date", DateTime.Now));
            para_list.Add(new SqlParameter("@update_uid", CurrentUser.user_id));
            para_list.Add(new SqlParameter("@update_date", DateTime.Now));
            if (db_op.ExecuteNonQuery(sql, para_list, false) < 0)
            {
                if (m_modify_mode)
                {
                    Logger.WriteLogError("modify position info fail");
                    MessageBox.Show("修改职位信息失败");
                    db_op.CloseDB();
                    return;
                }
                else
                {
                    Logger.WriteLogError("add position info fail");
                    MessageBox.Show("添加职位信息失败");
                    db_op.CloseDB();
                    return;
                }
            }
            db_op.CloseDB();
            if (OnChange != null)
                OnChange(sender, e);
            this.Close();
        }

        /// <summary>
        /// 删除-如果该职位有人则不能删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX2_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确定删除?", "删除职位信息", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.OK)
            {
                string pid = m_position_info.pid;
                DBOperator db_op = new DBOperator();
                if (db_op.ConnectDB() < 0)
                {
                    MessageBox.Show("无法连接服务器，请检查网络连接");
                    return;
                }
                List<SqlParameter> para_list = new List<SqlParameter>();
                string sql = "declare @user_count int;\n";
                sql += "select @user_count=COUNT(*) from user_info where u_pid=@pid;\n";
                sql += "if @user_count = 0 delete from position_info where pid=@pid";
                para_list.Add(new SqlParameter("@pid", pid));

                if (db_op.ExecuteNonQuery(sql, para_list, true) < 0)
                {
                    Logger.WriteLogError("delete position of [" + pid + "] fail");
                    MessageBox.Show("删除失败 该职位目前存在员工");
                }
                db_op.CloseDB();
                //send event to HomeUi to refresh datagridview
                if (OnChange != null)
                    OnChange(sender, e);
                this.Close();
            }
        }

        public delegate void PositionChange(object sender, EventArgs e);
        public event PositionChange OnChange;
        private bool m_modify_mode;
        private PositionInfo m_position_info;
    }

    class PositionInfo
    {
        public PositionInfo()
        {
            pid = "";
            p_did = "";
            d_name = "";
            p_name = "";
            p_info = "";
        }

        public string pid;
        public string p_did;
        public string d_name;
        public string p_name;
        public string p_info;
    }
}
